#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAXN (1000000)

double res, n = MAXN;
long thread_count;
long flag = 0;
pthread_mutex_t mutex;
void* thread_func(void* arg) {
    long arg_data = (long)arg;
    int len = (n + thread_count - 1) / thread_count;
    int st = arg_data * len;
    int en = st + len;
    double sum_t = 0.0;
    if (en > n) {
        en = n;
    }
    double factor = 1.0;
    if (st % 2) {
        factor = - factor;
    }
    for (int i = st; i < en; ++i) {
        sum_t += factor / (2 * i + 1);
        factor = - factor;
    }
    pthread_mutex_lock(&mutex);
    res += sum_t;
    pthread_mutex_unlock(&mutex);
    return 0;
}

int main(int argc, char** argv) {
    pthread_mutex_init(&mutex, NULL);
    thread_count = atoi(argv[1]);
    n = atoi(argv[2]);
    res = 0;
    pthread_t* thread_handles = malloc(thread_count * sizeof(pthread_t));
    for (long i = 0; i < thread_count; ++i) {
        pthread_create(&thread_handles[i], NULL, thread_func, (void*)i);
    }
    for (int i = 0; i < thread_count; ++i) {
        pthread_join(thread_handles[i], NULL);
    }
    res = 4.0 * res;
    printf("res: %f\n", res);
    free(thread_handles);
    pthread_mutex_destroy(&mutex);
    return 0;
}
